package com.itheima.mobilesafe69.service;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;
import com.itheima.mobilesafe69.db.dao.BlackNumberDao;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;

public class BlackNumberService extends Service {
	private InnerSmsReceiver mInnerSmsReceiver;
	private BlackNumberDao mDao;
	private TelephonyManager mTM;
	private MyPhoneStateLister mPhoneStateLister;
	private MyContentObserver mContentObserver;
	@Override
	public void onCreate() {
		mDao = BlackNumberDao.getInstance(getApplicationContext());
		
		//开启服务的时候,需要去拦截短信,动态注册接收到短信的广播接受者
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
		//提高此广播的优先级别
		intentFilter.setPriority(Integer.MAX_VALUE);
		//创建一个广播接受者对象
		mInnerSmsReceiver = new InnerSmsReceiver();
		registerReceiver(mInnerSmsReceiver, intentFilter);
		
		//1,电话管理者对象
		mTM = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		//2,监听电话状态
		mPhoneStateLister = new MyPhoneStateLister();
		mTM.listen(mPhoneStateLister, PhoneStateListener.LISTEN_CALL_STATE);
		super.onCreate();
	}
	
	class MyPhoneStateLister extends PhoneStateListener{
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:
				//空闲
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				//通话中
				break;
			case TelephonyManager.CALL_STATE_RINGING:
				//响铃
				endCall(incomingNumber);
				break;
			}
			super.onCallStateChanged(state, incomingNumber);
		}
	}
	
	class InnerSmsReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			//获取短信内容,判断其电话号码是否在黑名单数据库中
			Object[] objects = (Object[]) intent.getExtras().get("pdus");
			for (Object object : objects) {
				SmsMessage msg = SmsMessage.createFromPdu((byte[])object);
				
				String phone = msg.getOriginatingAddress();
				String content = msg.getMessageBody();
				
				//将此电话号码作为数据库中的查询条件,如果返回的mode值为1或者3的话,拦截短信
				int mode = mDao.find(phone);
				if(mode == 1 || mode == 3){
					//拦截(有序广播)
					abortBroadcast();
				}
			}
		}
	};
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	public void endCall(String incomingNumber) {
		//次电话是要被拦截的电话号码
		int mode = mDao.find(incomingNumber);
		if(mode == 2 || mode == 3){
			//如何去手动挂断一个电话
			//android老版本sdk有提供此挂断电话的方法,在新版本api中隐藏aidl()
//			TelephonyManager.endCall();
//			ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE));
			//因为ServiceManager对于开发者而已,隐藏的,所以不能直接调用其getService方法,通过反射的方式去做方法的调用
			try {
				//1,通过ServiceManager完整路径获取字节码
				Class<?> clazz = Class.forName("android.os.ServiceManager");
				//2,获取此类的指定名称,以及参数类型的方法
				Method method = clazz.getMethod("getService", String.class);
				//3,调用指定名称,参数类型的方法,最终返回一个IBinder对象
				//3.1(调用方法的对象,getService方法是静态,所以不需要对象也可以调用,传null)
				//3.2(参数值)
				IBinder binder = (IBinder) method.invoke(null, Context.TELEPHONY_SERVICE);
				//4,参照源码获取ITelephony实现类的对象
				ITelephony iTelephony = ITelephony.Stub.asInterface(binder);
				//5,调用隐藏在aidl文件中的endCall方法
				iTelephony.endCall();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			//6,删除数据库中通话记录
			deleteLog(incomingNumber);
		}
	}
	private void deleteLog(String incomingNumber) {
		//如果顺序执行删除电话号码代码的话,有可能数据还没有插入,就做上了删除操作,此条数据依然会存在于数据库中.
		//内容观察者,观察数据库的变化,先让其插入,在执行代码删除
		
		/*getContentResolver().delete(Uri.parse("content://call_log/calls"), "number = ?", new String[]{incomingNumber});*/

		mContentObserver = new MyContentObserver(new Handler(),incomingNumber);
		getContentResolver().registerContentObserver(
				Uri.parse("content://call_log/calls"), 
				true, 
				mContentObserver);
	}
	
	class MyContentObserver extends ContentObserver{
		private String phone;
		public MyContentObserver(Handler handler,String phone) {
			super(handler);
			this.phone = phone;
		}
		
		@Override
		public void onChange(boolean selfChange) {
			//一旦指定路径的数据库发生改变,调用此方法
			getContentResolver().delete(
					Uri.parse("content://call_log/calls"), "number = ?", new String[]{phone});
			super.onChange(selfChange);
		}
	}
	@Override
	public void onDestroy() {
		//关闭服务的是,需要去对注册过接收短信的广播,注销
		if(mInnerSmsReceiver!=null){
			unregisterReceiver(mInnerSmsReceiver);
		}
		//取消电话状态监听
		if(mTM!=null && mPhoneStateLister!=null){
			mTM.listen(mPhoneStateLister, PhoneStateListener.LISTEN_NONE);
		}
		
		//观察者进行注销
		if(mContentObserver!=null){
			getContentResolver().unregisterContentObserver(mContentObserver);
		}
		super.onDestroy();
	}
}
